package com.sky.task;


import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/*
 * 定义任务类 @Component ， 交给spring容器管理
 *     1.编写定义任务方法，定义执行的周期性功能代码
 *     2.设置定时时间
 *
 * */
@Component
public class OrderTask {

    @Autowired
    OrderMapper orderMapper;
    /*
     * 处理超时未支付订单处理：
     *         触发时间：每分钟
     *         业务流程：
     *               1.查询超时未支付的订单
     *               2.修改订单状态：已取消
     *
     * */

    @Scheduled(cron = "0 * * * * ?")
    public void OuttimeNotpay() {
        //1. 查询超时未支付的订单：select *from orders where status= 1 and order_time 超时了
        //1.1 获取当前时间，计算出超时时间节点
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
        //1.2 统计超时订单
        List<Orders> ordersList = orderMapper.selectByTimeAndStatus(Orders.PENDING_PAYMENT,time);

        //2.修改订单状态为：已取消
        //if (ordersList != null && ordersList.size() > 0) {
        if (ordersList != null && !ordersList.isEmpty()) {

            ordersList.forEach(o-> {
                System.out.println("正在取消超时未支付的订单：" + o.getNumber());
                orderMapper.update(Orders.builder()
                        .id(o.getId()) //订单id
                        .status(Orders.CANCELLED) //订单状态
                        .cancelReason(MessageConstant.OUTTIME_UPPLAY) //取消订单状态
                        .cancelTime(LocalDateTime.now()) //取消订单时间
                        .build());
            });
        }
    }

    /*
     * 处理已完成未确定订单处理：
     *         触发时间：凌晨3点
     *         业务流程：
     *               1.查询超时未支付的订单
     *               2.修改订单状态：已取消
     *
     * */
    @Scheduled(cron = "0 0 3 * * ?") //凌晨3点
    //@Scheduled(cron = "0/6 * * * * ?")
    public void OuttimeNotConfirm() {
        //1. 查询超时未支付的订单：select *from orders where status= 4 and order_time < 超时时间节点
        //1.1 获取当前时间，计算出超时时间节点
        LocalDateTime time = LocalDateTime.now().minusHours(3); //当前时间肯定是3点，往前推三个小时，就是12点
        //1.2 统计超时订单
        List<Orders> ordersList = orderMapper.selectByTimeAndStatus(Orders.DELIVERY_IN_PROGRESS,time);

        //2.修改订单状态为：已取消
        //if (ordersList != null && ordersList.size() > 0) {
        if (ordersList != null && !ordersList.isEmpty()) {

            ordersList.forEach(o-> {
                System.out.println("正在确定超时未确认订单：" + o.getNumber());
                orderMapper.update(Orders.builder()
                        .id(o.getId()) //订单id
                        .status(Orders.COMPLETED) //订单状态
                        .build());
            });
        }
    }
}
